﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace 历史积累
{
    /// <summary>
    /// 采样校准
    /// </summary>
    public class SamplingCalibration
    {
        /// <summary>
        /// 测量记录
        /// </summary>
        public List<MeasuringRecord> RecordLsit { get; }

        /// <summary>
        /// 采样校准
        /// </summary>
        /// <param name="records">测量记录</param>
        public SamplingCalibration(List<MeasuringRecord> records)
        {
            RecordLsit = records;
            KValues = new Dictionary<MeasuringRecord, double>();
        }

        /// <summary>
        /// 校准K值记录
        /// </summary>
        private Dictionary<MeasuringRecord, double> KValues { get; }

        /// <summary>
        /// 校准采样数据
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public double? Calculate(double value)
        {

            var lest = RecordLsit.LastOrDefault(a => a.Sampling < value);
            var First = RecordLsit.FirstOrDefault(a => a.Sampling > value);
            if (lest != null && First != null)
            {
                if (!KValues.TryGetValue(lest, out var k))
                {
                    KValues[lest] = k = (First.Sampling - lest.Sampling) / (First.Practical - lest.Practical);
                }
                return (value - lest.Sampling) * k + lest.Practical;
            }
            return null;
        }
    }

    /// <summary>
    /// 采样记录
    /// </summary>
    public class MeasuringRecord
    {
        /// <summary>
        /// 采样值
        /// </summary>
        public double Sampling { get; set; }

        /// <summary>
        /// 实际测量值
        /// </summary>
        public double Practical { get; set; }
    }
}